package service

import (
	"errors"
	"fmt"

	"core/entity"

	"core/db"

	"core/api/controller/response"

	"gopkg.in/yaml.v2"
)

func ListHubNodeDefinitions(pageNum, pageSize int) (pageResponse *response.PageResponse, err error) {
	definitions := make([]entity.HubNodeDefinition, 0)
	pageResponse = new(response.PageResponse)

	err = db.DB.Offset((pageNum - 1) * pageSize).Limit(pageSize).Find(&definitions).Error
	if err != nil {
		return nil, err
	}
	for index, definition := range definitions {
		var hubNodeDefinitionVersions []entity.HubNodeDefinitionVersion
		var versions []string
		err = db.DB.Where("ref = ?", definition.Ref).Find(&hubNodeDefinitionVersions).Error
		if err != nil {
			return nil, err
		}
		for _, hubNodeDefinitionVersion := range hubNodeDefinitionVersions {
			versions = append(versions, hubNodeDefinitionVersion.Version)
		}
		definitions[index].Versions = versions
	}

	var total int
	err = db.DB.Model(&entity.HubNodeDefinition{}).Count(&total).Error
	if err != nil {
		return nil, err
	}

	pageResponse.Total = total
	pageResponse.List = definitions
	pageResponse.PageNum = pageNum
	pageResponse.PageSize = pageSize

	pageResponse.Size = 0
	pageResponse.StartRow = 0
	pageResponse.EndRow = 0

	pageResponse.PrePage = pageNum - 1

	return pageResponse, nil
}

func ConvertToBytes(src []interface{}) (dst []byte) {
	fmt.Println(src)
	fmt.Println(len(src))
	for i := 0; i < len(src); i += 1 {
		dst = append(dst, src[i].(uint8))
	}
	return dst
}

func CreateHubNodeDefintion(dsl string, name string) (err error) {
	var hubNodeDefinition entity.HubNodeDefinition
	var hubNodeDefinitionVersion entity.HubNodeDefinitionVersion

	content := make(map[string]interface{})

	err = yaml.Unmarshal([]byte(dsl), &content)
	if err != nil {
		return err
	}

	hubNodeDefinition.Name = name

	if val, ok := content["ref"]; ok {
		hubNodeDefinition.ID = val.(string)
		hubNodeDefinition.Ref = val.(string)
	} else {
		return errors.New("ref 不存在")
	}

	if val, ok := content["version"]; ok {
		hubNodeDefinitionVersion.Version = val.(string)
	} else {
		return errors.New("version 不存在")
	}

	if val, ok := content["resultFile"]; ok {
		hubNodeDefinitionVersion.ResultFile = val.(string)
	}

	fmt.Println("-----------------------------------------------")
	if val, ok := content["inputParameters"]; ok {
		fmt.Println("----------------------------------------2-------")

		hubNodeDefinitionVersion.InputParameters = ConvertToBytes(val.([]interface{}))
	}
	fmt.Println("-----------------------------------------------")

	if val, ok := content["outputParameters"]; ok {
		fmt.Println("-----------------------------------------2------")

		hubNodeDefinitionVersion.OutputParameters = ConvertToBytes(val.([]interface{}))

	}
	fmt.Println("-----------------------------------------------")

	err = db.DB.Create(hubNodeDefinition).Error
	if err != nil {
		return err
	}

	err = db.DB.Create(hubNodeDefinitionVersion).Error
	if err != nil {
		return err
	}

	return nil
}
